package whu;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MyClass {
    public MyClass(){};
    @InitMethod
    public void Init(){
        System.out.println("调用Init方法");
    }
    String className = "";
    Object ob = null;
    Class c = null;

    public Object createIns()throws ClassNotFoundException {
        try (InputStream input = MyClass.class.getResourceAsStream("/default.properties")){
            className = "";
            if(input == null){ return null;}
            int size = input.available();
            boolean is = false;
            StringBuilder b = new StringBuilder();
            char temp;
            for(int i=0;i<size;i++){
                temp = (char)input.read();
                if(temp == ' '){
                    if(b.toString().equals("class")) {
                        is = true;
                    }
                    b.delete(0,b.length());
                }else if(temp == '\n'||temp == '\r'){
                    if(is){
                        className = b.toString();
                        break;
                    }
                    b.delete(0,b.length());
                }
                else b.append(temp);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        className = "whu."+className;
        c = Class.forName(className);//返回与带有给定字符串名的类或接口相关联的 Class 对象

        try {
            ob = c.newInstance();
            return ob;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }
    public void InvokeInit(){
        Method[] methods = c.getMethods();
        for(Method m :methods){
            if(m.isAnnotationPresent(InitMethod.class)){
                try {
                    m.invoke(ob);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
